﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.DAL;
using Medianamik.Core.Sugar;
using Medianamik.UI.Web.MVP.View;
using Telerik.Web.UI;

namespace Medianamik.UI.Web.MVP.Presentation
{
    public abstract class ModulePresenterWithNodeTypePropertyGrid<TView> : ModulePresenterWithGridBase<NodeTypeProperty, TView>
        where TView : IModuleViewWithNodeTypePropertyGrid
    {
        protected virtual Guid? TypeId
        {
            get
            {
                Guid? typeId = null;
                if (View.QueryString[DefaultParamNames.TypeID] != null)
                {
                    View.QueryString[DefaultParamNames.TypeID].IsGuidInline(ref typeId);
                }
                return typeId;
            }
        }

        private NodeType _type;
        private NodeType Type
        {
            get
            {
                if(_type == null)
                {
                    _type = NodeTypeManager.GetNodeType(TypeId.Value);
                }
                return _type;
            }
        }
        
        protected ModulePresenterWithNodeTypePropertyGrid(TView view)
            : base(view)
        {
        }

        protected override void Initialize(object sender, EventArgs e)
        {
            if (TypeId == null)
            {
                if (View.RootListingPageUrl == null)
                    throw new ApplicationException("NodeTypeId and View.RootListingPageUrl are null");
                View.Redirect(View.RootListingPageUrl);
            }

            View.Grid.OrderChanged += OnNodePropertyOrderChanged;

            base.Initialize(sender, e);
        }

        protected virtual void OnNodePropertyOrderChanged(object sender, OrderChangedEventArgs e)
        {
            if (e.Id != null && e.Id != Guid.Empty && e.DestinationId != Guid.Empty)
            {
                Type.MoveProperty(e.Id.Value, e.DestinationId, e.DropPosition);

                NodeTypeManager.SaveType(Type);
                Bind();
            }
        }

        protected override string AddUrl
        {
            get
            {
                string baseUrl = base.AddUrl;
                if(baseUrl != null)
                {
                    baseUrl = baseUrl.AddParam(DefaultParamNames.TypeID, TypeId.Value);
                }
                return baseUrl;
            }
        }

        protected override void SetCustomGridColumnsAtCreation(GridItem item)
        {
            base.SetCustomGridColumnsAtCreation(item);

            SetDeleteButton((LinkButton)item.FindControl(View.DeleteButtonId), null);
        }

        protected override void SetGridRowCSS(GridDataItem item, NodeTypeProperty nodeType)
        {
            base.SetGridRowCSS(item, nodeType);

            if (nodeType.IsGenerated || nodeType.TypeID != Type.ID)
            {
                item.CssClass = "rgRow ElementNonTraduit";
            }
        }

        protected override void SetCustomGridColumns(GridItem item, NodeTypeProperty nodeType)
        {
            base.SetCustomGridColumns(item, nodeType);

            SetEditButton((HyperLink)item.FindControl(View.EditButtonId), nodeType);
            SetDeleteButton((LinkButton)item.FindControl(View.DeleteButtonId), nodeType);
        }

        protected virtual void SetEditButton(HyperLink editButton, NodeTypeProperty nodeTypeProp)
        {
            if (editButton != null)
            {
                editButton.NavigateUrl = View.EditPageUrl.AddParam(DefaultParamNames.TypeID, nodeTypeProp.ID)
                                            .AddParam(DefaultParamNames.ReturnURL, EditReturnUrl.UrlEncodeBase64());
            }
        }

        protected virtual void SetDeleteButton(LinkButton deleteButton, NodeTypeProperty nodeTypeProp)
        {
            if (deleteButton != null)
            {
                if (nodeTypeProp != null && (nodeTypeProp.IsGenerated || nodeTypeProp.TypeID != Type.ID))
                {
                    deleteButton.Enabled = false;
                    deleteButton.Text = "<img alt=\"\" src=\"/medianamik/images/Icones/Ico_SupprimerInactif.gif\" />";
                    deleteButton.OnClientClick = "";
                }
                else
                {
                    deleteButton.Command += OnNodePropertyDelete;
                }
            }
        }

        protected virtual void OnNodePropertyDelete(object sender, CommandEventArgs e)
        {
            if(e.CommandName == "delete" && e.CommandArgument != null)
            {
                Guid nodeTypePropId;
                if(e.CommandArgument.ToString().IsGuidInline(out nodeTypePropId))
                {
                    NodeTypeManager.DeleteTypeProperty(nodeTypePropId);
                    Bind();
                }
            }
        }

        protected override void SetNameColumn(ITextControl nameGridItem, NodeTypeProperty nodeTypeProp)
        {
            var sb = new StringBuilder();

            if(ChildrenListingPageUrl != null)
            {
                sb.AppendFormat("<a href=\"{0}\">{1}</a>",
                                ChildrenListingPageUrl.AddParam(ChildrenListingPageParamName, nodeTypeProp.ID),
                                nodeTypeProp.GetLocalizedName(MedianamikContext.Current.CurrentUICulture));
            }
            else
            {
                sb.Append(nodeTypeProp.GetLocalizedName(MedianamikContext.Current.CurrentUICulture));
            }

            if (nodeTypeProp.IsRequired)
            {
                sb.Append("&nbsp;&nbsp;<img src=\"/Medianamik/images/Icones/Ico_ProprieteObligatoire.png\" class=\"IconeLabel\" alt=\"\" />");
            }
            if (nodeTypeProp.IsLanguageNeutral)
            {
                sb.Append("&nbsp;&nbsp;<img src=\"/Medianamik/images/Icones/Ico_ProprieteNeutreLangue.png\" class=\"IconeLabel\" alt=\"\" />");
            }

            nameGridItem.Text = sb.ToString();
        }               

        protected virtual List<NodeTypeProperty> GetNodeProperties()
        {
            var properties = Type.Properties
                .AsEnumerable();

            if(View.IncludeInheritedProperties)
            {
                properties = properties.Concat(Type.InheritedProperties.Where(p => !p.IsDeleted));
            }
            if (!View.IncludeGeneratedProperties)
            {
                properties = properties.Where(p => !p.IsGenerated);
            }

            return properties
                .Where(p => !View.ExcludedGroupNames.Contains(p.GroupName))
                .ToList();
        }

        protected override PagedCollection<NodeTypeProperty> GetData()
        {
            var properties = GetNodeProperties()
                .OrderBy(p => Type.GetPropertyPosition(p.ID)).ToList();

            if(View.AllowPaging)
            {
                properties = properties
                    .Skip((PageIndex - 1)*PageSize)
                    .Take(PageSize)
                    .ToList();
            }

            return new PagedCollection<NodeTypeProperty>(properties, properties.Count);
        }
    }
}